<!DOCTYPE html>
<html>
<head>
    <title>回测报告</title>
    <meta charset="utf-8">
    <!-- 内嵌Plotly脚本或使用CDN备用方式 -->
    <script>
    $plotly_js
    </script>
    <!-- Plotly脚本内嵌失败时的CDN备用 -->
    <script>
    if (typeof Plotly === 'undefined') {
        console.log('内嵌Plotly脚本加载失败，切换为使用CDN版本');
        var script = document.createElement('script');
        script.src = 'https://cdn.plot.ly/plotly-latest.min.js';
        document.head.appendChild(script);
    } else {
        console.log('Plotly脚本已成功内嵌加载');
    }
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
            padding: 12px;
            background-color: #f8f9fa;
            border-radius: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header-left {
            display: flex;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            margin-right: 15px;
        }
        .header p {
            margin: 5px 0;
        }
        .metrics-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        .metrics-table th, .metrics-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .metrics-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .metrics-table tr:hover {
            background-color: #f5f5f5;
        }
        .chart-container {
            margin-top: 30px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
        }
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 15px;
            margin-bottom: 30px;
        }
        .metric-card {
            background-color: #f8f9fa;
            padding: 12px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            text-align: center;
            transition: all 0.2s ease;
            cursor: pointer;
        }
        .metric-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            background-color: #f0f0f0;
        }
        .metric-card h3 {
            margin: 0 0 8px 0;
            color: #333;
            font-size: 0.95em;
        }
        .metric-value {
            font-size: 1.2em;
            font-weight: bold;
            color: #2c3e50;
        }
        .negative-value {
            color: #27ae60; /* 绿色 */
        }
        .tooltip {
            display: none;
            position: absolute;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.85em;
            max-width: 200px;
            z-index: 100;
        }
        .section-title {
            margin-top: 40px;
            margin-bottom: 20px;
            color: #2c3e50;
            font-size: 1.5em;
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
        }
        .trade-filter {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            gap: 15px;
        }
        .trade-filter input, .trade-filter button {
            padding: 8px 12px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .trade-filter button {
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .trade-filter button:hover {
            background-color: #3e8e41;
        }
        .trades-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
            font-size: 0.9em;
        }
        .trades-table th, .trades-table td {
            padding: 8px 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .trades-table th {
            background-color: #f8f9fa;
            position: sticky;
            top: 0;
        }
        .trades-table tr:hover {
            background-color: #f5f5f5;
        }
        .trades-container {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 5px;
            position: relative; /* 为加载动画添加相对定位 */
        }
        .buy {
            color: #e74c3c;
        }
        .sell {
            color: #27ae60;
        }
        .date-group-header {
            background-color: #edf2f7;
            font-weight: bold;
            text-align: left;
            padding: 10px;
            border-bottom: 1px solid #cbd5e0;
        }
        .no-trades {
            text-align: center;
            padding: 20px;
            color: #718096;
            font-style: italic;
        }
        /* 添加标签页样式 */
        .tabs {
            margin-top: 30px;
            border-bottom: 1px solid #ddd;
        }
        .tab-button {
            background-color: inherit;
            border: none;
            outline: none;
            cursor: pointer;
            padding: 14px 16px;
            font-size: 16px;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
            transition: all 0.3s ease;
        }
        .tab-button:hover {
            background-color: #f1f1f1;
        }
        .tab-button.active {
            background-color: #4CAF50;
            color: white;
            border-bottom: none;
        }
        .tab-content {
            display: none;
            padding: 20px 0;
            animation: fadeEffect 1s;
        }
        @keyframes fadeEffect {
            from {opacity: 0;}
            to {opacity: 1;}
        }
        .tab-content.active {
            display: block;
        }
        
        /* 现金流标签样式 */
        .cashflow-tag {
            display: inline-block;
            font-size: 11px;
            padding: 1px 5px;
            border-radius: 3px;
            margin-left: 5px;
            color: white;
        }
        
        .cashflow-interest {
            background-color: #17a2b8; /* 蓝色 - 利息 */
        }
        
        .cashflow-principal {
            background-color: #fd7e14; /* 橙色 - 本金 */
        }
        
        .cashflow-maturity {
            background-color: #6f42c1; /* 紫色 - 到期 */
        }
        
        /* 加载动画样式 */
        .loading-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            display: none;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            color: white;
        }
        .loading-spinner {
            border: 5px solid #f3f3f3;
            border-top: 5px solid #3498db;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-left">
                <h1>回测报告</h1>
                <p>生成时间: $timestamp</p>
            </div>
            <p>回测区间: $start_date 至 $end_date</p>
        </div>
        
        <div class="metrics-grid">
            <div class="metric-card">
                <h3>总收益率</h3>
                <div class="metric-value">$total_return</div>
            </div>
            <div class="metric-card">
                <h3>年化收益率</h3>
                <div class="metric-value">$annualized_return</div>
            </div>
            <div class="metric-card">
                <h3>最大回撤</h3>
                <div class="metric-value">$max_drawdown</div>
            </div>
            <div class="metric-card">
                <h3>夏普比率</h3>
                <div class="metric-value">$sharpe_ratio</div>
            </div>
            <div class="metric-card">
                <h3>索提诺比率</h3>
                <div class="metric-value">$sortino_ratio</div>
            </div>
            <div class="metric-card">
                <h3>卡玛比率</h3>
                <div class="metric-value">$calmar_ratio</div>
            </div>
            <div class="metric-card">
                <h3>年化波动率</h3>
                <div class="metric-value">$volatility</div>
            </div>
            <div class="metric-card">
                <h3>胜率</h3>
                <div class="metric-value">$win_rate</div>
            </div>
            <div class="metric-card">
                <h3>换手率</h3>
                <div class="metric-value">$turnover_rate</div>
            </div>
            <div class="metric-card">
                <h3>平均持仓标的数</h3>
                <div class="metric-value">$avg_holdings_count</div>
            </div>
        </div>
        
        <!-- 标签页按钮 -->
        <div class="tabs">
            <button class="tab-button active" onclick="openTab(event, 'overview-tab')">策略概览</button>
            <button class="tab-button" onclick="openTab(event, 'trades-tab')">交易记录</button>
            <button class="tab-button" onclick="openTab(event, 'holdings-tab')">持仓记录</button>
            <button class="tab-button" onclick="openTab(event, 'cashflows-tab')">现金流记录</button>
        </div>
        
        <!-- 策略概览标签页 -->
        <div id="overview-tab" class="tab-content active">
            <h2 class="section-title">策略表现分析</h2>
            <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
                <button id="download-netvalue-btn" class="btn" style="padding: 8px 15px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">下载每日净值数据</button>
            </div>
            <div class="chart-container" id="perf-chart"></div>
            
            <h2 class="section-title">持仓占比变化</h2>
            <div class="chart-container" id="pos-chart"></div>
        </div>
        
        <!-- 交易记录标签页 -->
        <div id="trades-tab" class="tab-content">
            <h2 class="section-title">交易记录</h2>
            <div class="trade-filter">
                <label for="start-date-filter">开始日期:</label>
                <input type="date" id="start-date-filter" value="$start_date">
                <label for="end-date-filter">结束日期:</label>
                <input type="date" id="end-date-filter" value="$end_date">
                <button id="filter-trades-btn">查询交易记录</button>
            </div>
            <div class="trades-container" id="trades-table-container">
                <table class="trades-table" id="trades-table">
                    <thead>
                        <tr>
                            <th>交易时间</th>
                            <th>标的代码</th>
                            <th>方向</th>
                            <th>价格</th>
                            <th>数量</th>
                            <th>交易金额</th>
                            <th>手续费</th>
                            <th>滑点成本</th>
                            <th>总成本</th>
                        </tr>
                    </thead>
                    <tbody id="trades-body">
                        <!-- 交易记录将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 持仓记录标签页 -->
        <div id="holdings-tab" class="tab-content">
            <h2 class="section-title">持仓记录</h2>
            <div class="trade-filter">
                <label for="holdings-start-date-filter">开始日期:</label>
                <input type="date" id="holdings-start-date-filter" value="$start_date">
                <label for="holdings-end-date-filter">结束日期:</label>
                <input type="date" id="holdings-end-date-filter" value="$end_date">
                <button id="filter-holdings-btn">查询持仓记录</button>
            </div>
            <div class="trades-container" id="holdings-table-container">
                <table class="trades-table" id="holdings-table">
                    <thead>
                        <tr>
                            <th>日期</th>
                            <th>标的代码</th>
                            <th>持仓数量</th>
                            <th>收盘价格</th>
                            <th>持仓市值</th>
                            <th>持仓占比</th>
                            <th>成本价</th>
                            <th>久期</th>
                            <th>浮动盈亏</th>
                        </tr>
                    </thead>
                    <tbody id="holdings-body">
                        <!-- 持仓记录将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 现金流记录标签页 -->
        <div id="cashflows-tab" class="tab-content">
            <h2 class="section-title">现金流记录</h2>
            <div class="trade-filter">
                <label for="cashflows-start-date-filter">开始日期:</label>
                <input type="date" id="cashflows-start-date-filter" value="$start_date">
                <label for="cashflows-end-date-filter">结束日期:</label>
                <input type="date" id="cashflows-end-date-filter" value="$end_date">
                <button id="filter-cashflows-btn">查询现金流记录</button>
            </div>
            <div class="trades-container" id="cashflows-table-container">
                <table class="trades-table" id="cashflows-table">
                    <thead>
                        <tr>
                            <th>时间</th>
                            <th>标的代码</th>
                            <th>类型</th>
                            <th>金额</th>
                            <th>流向</th>
                            <th>关联持仓</th>
                        </tr>
                    </thead>
                    <tbody id="cashflows-body">
                        <!-- 现金流记录将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script>
        // 全局变量
        var tradesData = $trades_json || [];
        var holdingsData = $positions_json || {};
        var cashflowsData = $cashflows_json || [];
        var perfPlotlyData = $perf_plotly_json || {};
        
        // 标记标签页是否已加载
        var tabsLoaded = {
            'overview-tab': true,  // 概览标签页总是默认加载
            'trades-tab': false,
            'holdings-tab': false,
            'cashflows-tab': false
        };
        
        // 缓存已渲染的内容和查询条件
        var tabsCache = {
            'trades-tab': {
                content: null,
                queryParams: null,
                scrollPosition: 0 // 保存滚动位置
            },
            'holdings-tab': {
                content: null,
                queryParams: null,
                scrollPosition: 0 // 保存滚动位置
            },
            'cashflows-tab': {
                content: null,
                queryParams: null,
                scrollPosition: 0 // 保存滚动位置
            }
        };
        
        // 显示加载中动画的函数
        function showLoading(tabId) {
            var loadingId = tabId + '-loading';
            var existingLoadingDiv = document.getElementById(loadingId);
            
            // 如果已存在加载动画，只需显示它
            if (existingLoadingDiv) {
                try {
                    existingLoadingDiv.parentNode.removeChild(existingLoadingDiv);
                } catch(e) {
                    console.error('移除现有加载动画失败:', e);
                }
            }
            
            // 找到内容区域
            var contentArea;
            if (tabId === 'trades-tab') {
                contentArea = document.getElementById('trades-table-container');
            } else if (tabId === 'holdings-tab') {
                contentArea = document.getElementById('holdings-table-container');
            } else if (tabId === 'cashflows-tab') {
                contentArea = document.getElementById('cashflows-table-container');
            } else {
                // 默认找到整个标签页
                contentArea = document.getElementById(tabId);
            }
            
            if (!contentArea) {
                console.error('找不到内容区域:', tabId);
                return;
            }
            
            // 创建一个新的加载动画容器
            var loadingDiv = document.createElement('div');
            loadingDiv.id = loadingId;
            loadingDiv.className = 'loading-container';
            loadingDiv.innerHTML = `
                <div class="loading-spinner"></div>
                <p>正在加载数据...</p>
            `;
            
            // 设置样式使其覆盖在内容区域上
            loadingDiv.style.position = 'absolute';
            loadingDiv.style.top = '0';
            loadingDiv.style.left = '0';
            loadingDiv.style.width = '100%';
            loadingDiv.style.height = '100%';
            loadingDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
            loadingDiv.style.zIndex = '1000';
            loadingDiv.style.display = 'flex';
            loadingDiv.style.justifyContent = 'center';
            loadingDiv.style.alignItems = 'center';
            loadingDiv.style.flexDirection = 'column';
            loadingDiv.style.color = 'white';
            
            // 设置表格容器为相对定位，以便绝对定位的加载动画能正确覆盖
            contentArea.style.position = 'relative';
            
            // 添加到内容区域
            contentArea.appendChild(loadingDiv);
            console.log('显示加载动画:', tabId);
        }
        
        // 隐藏加载动画的函数
        function hideLoading(tabId) {
            var loadingDiv = document.getElementById(tabId + '-loading');
            if (loadingDiv) {
                try {
                    loadingDiv.parentNode.removeChild(loadingDiv);
                    console.log('隐藏加载动画:', tabId);
                } catch(e) {
                    console.error('隐藏加载动画失败:', e);
                    // 如果移除失败，直接隐藏
                    loadingDiv.style.display = 'none';
                }
            }
        }
        
        // 格式化日期
        function formatDate(dateStr) {
            var date = new Date(dateStr);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            });
        }
        
        // 格式化时间
        function formatDateTime(dateStr) {
            var date = new Date(dateStr);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }
        
        // 格式化交易方向
        function formatDirection(direction) {
            return direction === 1 ? '<span class="buy">买入</span>' : '<span class="sell">卖出</span>';
        }
        
        // 格式化金额
        function formatMoney(value) {
            return parseFloat(value).toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }
        
        // 填充交易记录表格
        function fillTradesTable(trades) {
            var tradesBody = document.getElementById('trades-body');
            tradesBody.innerHTML = '';
            
            if (!trades || trades.length === 0) {
                tradesBody.innerHTML = '<tr><td colspan="9" class="no-trades">该时间段内没有交易记录</td></tr>';
                return;
            }
            
            // 按日期对交易记录进行分组
            var tradesByDate = {};
            trades.forEach(function(trade) {
                var date = formatDate(trade.timestamp);
                if (!tradesByDate[date]) {
                    tradesByDate[date] = [];
                }
                tradesByDate[date].push(trade);
            });
            
            // 按日期顺序填充交易记录
            var dates = Object.keys(tradesByDate).sort();
            dates.forEach(function(date) {
                // 添加日期分组标题
                var dateRow = document.createElement('tr');
                var dateCell = document.createElement('td');
                dateCell.className = 'date-group-header';
                dateCell.colSpan = 9;
                dateCell.textContent = '交易日期: ' + date;
                dateRow.appendChild(dateCell);
                tradesBody.appendChild(dateRow);
                
                // 添加该日期下的所有交易
                tradesByDate[date].sort(function(a, b) {
                    return new Date(a.timestamp) - new Date(b.timestamp);
                }).forEach(function(trade) {
                    var row = document.createElement('tr');
                    
                    // 交易时间
                    var timeCell = document.createElement('td');
                    timeCell.textContent = formatDateTime(trade.timestamp);
                    row.appendChild(timeCell);
                    
                    // 标的代码
                    var symbolCell = document.createElement('td');
                    symbolCell.textContent = trade.symbol;
                    row.appendChild(symbolCell);
                    
                    // 方向
                    var directionCell = document.createElement('td');
                    directionCell.innerHTML = formatDirection(trade.direction);
                    row.appendChild(directionCell);
                    
                    // 价格
                    var priceCell = document.createElement('td');
                    priceCell.textContent = formatMoney(trade.price);
                    row.appendChild(priceCell);
                    
                    // 数量
                    var quantityCell = document.createElement('td');
                    quantityCell.textContent = formatMoney(Math.abs(trade.quantity));
                    row.appendChild(quantityCell);
                    
                    // 交易金额
                    var amountCell = document.createElement('td');
                    var amount = Math.abs(trade.price * trade.quantity);
                    amountCell.textContent = formatMoney(amount);
                    row.appendChild(amountCell);
                    
                    // 手续费
                    var commissionCell = document.createElement('td');
                    commissionCell.textContent = formatMoney(trade.commission);
                    row.appendChild(commissionCell);
                    
                    // 滑点成本
                    var slippageCell = document.createElement('td');
                    var slippage = (trade.transaction_cost || 0) - (trade.commission || 0);
                    slippageCell.textContent = formatMoney(slippage);
                    row.appendChild(slippageCell);
                    
                    // 总成本
                    var totalCostCell = document.createElement('td');
                    totalCostCell.textContent = formatMoney(trade.transaction_cost || 0);
                    row.appendChild(totalCostCell);
                    
                    tradesBody.appendChild(row);
                });
            });
        }
        
        // 填充持仓记录表格
        function fillHoldingsTable(holdings, startDate, endDate) {
            var holdingsBody = document.getElementById('holdings-body');
                holdingsBody.innerHTML = '';
            
            if (!holdings || Object.keys(holdings).length === 0) {
                holdingsBody.innerHTML = '<tr><td colspan="9" class="no-trades">该时间段内没有持仓记录</td></tr>';
                return;
            }
            
            // 获取日期范围内的数据
            var filteredDates = Object.keys(holdings).filter(function(dateStr) {
                var date = new Date(dateStr);
                return date >= startDate && date <= endDate;
            }).sort();
            
            if (filteredDates.length === 0) {
                holdingsBody.innerHTML = '<tr><td colspan="9" class="no-trades">该时间段内没有持仓记录</td></tr>';
                return;
            }
            
            // 按日期添加持仓记录
            filteredDates.forEach(function(dateStr) {
                // 获取当日现金量
                var cashAmount = holdings[dateStr + '_cash'] || 0;

                // 计算持仓总市值
                var totalMarketValue = holdings[dateStr].reduce(function(total, position) {
                    return total + position.market_value;
                }, 0);
                
                // 计算总资产（持仓市值+现金）
                var totalAssets = totalMarketValue + cashAmount;
                
                // 计算持仓占比
                var positionPercentage = totalAssets > 0 ? (totalMarketValue / totalAssets * 100).toFixed(2) + '%' : '0%';
                
                // 按持仓市值从大到小排序
                var sortedPositions = holdings[dateStr].slice().sort(function(a, b) {
                    return b.market_value - a.market_value;
                });
                
                // 添加日期分组标题
                var dateRow = document.createElement('tr');
                var dateCell = document.createElement('td');
                dateCell.className = 'date-group-header';
                dateCell.colSpan = 9;
                dateCell.textContent = '日期: ' + formatDate(dateStr) + 
                                    ' (持仓市值: ' + formatMoney(totalMarketValue) + 
                                    ', 现金: ' + formatMoney(cashAmount) + 
                                    ', 总资产: ' + formatMoney(totalAssets) + 
                                    ', 持仓占比: ' + positionPercentage + ')';
                dateRow.appendChild(dateCell);
                holdingsBody.appendChild(dateRow);
                
                // 检查是否有持仓
                if (!sortedPositions || sortedPositions.length === 0) {
                    var noHoldingsRow = document.createElement('tr');
                    var noHoldingsCell = document.createElement('td');
                    noHoldingsCell.colSpan = 9;
                    noHoldingsCell.className = 'no-trades';
                    noHoldingsCell.textContent = '该日期没有持仓';
                    noHoldingsRow.appendChild(noHoldingsCell);
                    holdingsBody.appendChild(noHoldingsRow);
                    return;
                }
                
                // 添加每个持仓记录
                sortedPositions.forEach(function(position) {
                    var row = document.createElement('tr');
                    
                    // 日期
                    var dateCell = document.createElement('td');
                    dateCell.textContent = formatDate(dateStr);
                    row.appendChild(dateCell);
                    
                    // 标的代码并添加现金流标签
                    var symbolCell = document.createElement('td');
                    
                    // 检查该日期该标的是否有现金流事件
                    var symbolWithTags = position.symbol;
                    var dateCashflows = cashflowsData.filter(function(cf) {
                        var cfDate = formatDate(cf.timestamp);
                        return cfDate === formatDate(dateStr) && cf.symbol === position.symbol;
                    });
                    
                    if (dateCashflows.length > 0) {
                        // 对不同类型的现金流创建不同的标签
                        var tags = {};
                        dateCashflows.forEach(function(cf) {
                            tags[cf.type] = true;
                        });
                        
                        // 添加标签
                        if (tags['INTEREST']) {
                            symbolWithTags += ' <span class="cashflow-tag cashflow-interest">息</span>';
                        }
                        if (tags['PRINCIPAL']) {
                            symbolWithTags += ' <span class="cashflow-tag cashflow-principal">本</span>';
                        }
                        if (tags['MATURITY']) {
                            symbolWithTags += ' <span class="cashflow-tag cashflow-maturity">到</span>';
                        }
                    }
                    
                    symbolCell.innerHTML = symbolWithTags;
                    row.appendChild(symbolCell);
                    
                    // 持仓数量
                    var quantityCell = document.createElement('td');
                    quantityCell.textContent = formatMoney(position.quantity);
                    row.appendChild(quantityCell);
                    
                    // 收盘价格
                    var priceCell = document.createElement('td');
                    priceCell.textContent = formatMoney(position.price);
                    row.appendChild(priceCell);
                    
                    // 持仓市值
                    var valueCell = document.createElement('td');
                    valueCell.textContent = formatMoney(position.market_value);
                    row.appendChild(valueCell);
                    
                    // 持仓占比
                    var percentageCell = document.createElement('td');
                    var percentage = totalMarketValue > 0 ? (position.market_value / totalMarketValue * 100) : 0;
                    percentageCell.textContent = percentage.toFixed(2) + '%';
                    row.appendChild(percentageCell);
                    
                    // 成本价
                    var costPriceCell = document.createElement('td');
                    costPriceCell.textContent = formatMoney(position.avg_price);
                    row.appendChild(costPriceCell);
                    
                    // 久期
                    var durationCell = document.createElement('td');
                    durationCell.textContent = formatMoney(position.duration);
                    row.appendChild(durationCell);
                    
                    // 浮动盈亏
                    var pnlCell = document.createElement('td');
                    pnlCell.textContent = formatMoney(position.market_value - (position.quantity * position.avg_price));
                    if (position.market_value < (position.quantity * position.avg_price)) {
                        pnlCell.className = 'negative-value';
                    } else if (position.market_value > (position.quantity * position.avg_price)) {
                        pnlCell.className = 'positive-value';
                    }
                    row.appendChild(pnlCell);
                    
                    holdingsBody.appendChild(row);
                });
            });
        }
        
        // 填充现金流记录表格
        function fillCashflowsTable(cashflows, startDate, endDate) {
            var cashflowsBody = document.getElementById('cashflows-body');
            cashflowsBody.innerHTML = '';
            
            if (!cashflows || cashflows.length === 0) {
                cashflowsBody.innerHTML = '<tr><td colspan="6" class="no-trades">该时间段内没有现金流记录</td></tr>';
                return;
            }
            
            // 按日期对现金流记录进行分组
            var cashflowsByDate = {};
            cashflows.forEach(function(cashflow) {
                var date = formatDate(cashflow.timestamp);
                if (!cashflowsByDate[date]) {
                    cashflowsByDate[date] = [];
                }
                cashflowsByDate[date].push(cashflow);
            });
            
            // 按日期顺序填充现金流记录
            var dates = Object.keys(cashflowsByDate).sort();
            dates.forEach(function(date) {
                // 添加日期分组标题
                var dateRow = document.createElement('tr');
                var dateCell = document.createElement('td');
                dateCell.className = 'date-group-header';
                dateCell.colSpan = 6;
                dateCell.textContent = '日期: ' + date;
                dateRow.appendChild(dateCell);
                cashflowsBody.appendChild(dateRow);
                
                // 添加该日期下的所有现金流
                cashflowsByDate[date].sort(function(a, b) {
                    return new Date(a.timestamp) - new Date(b.timestamp);
                }).forEach(function(cashflow) {
                    var row = document.createElement('tr');
                    
                    // 时间
                    var timeCell = document.createElement('td');
                    timeCell.textContent = formatDateTime(cashflow.timestamp);
                    row.appendChild(timeCell);
                    
                    // 标的代码
                    var symbolCell = document.createElement('td');
                    symbolCell.textContent = cashflow.symbol;
                    row.appendChild(symbolCell);
                    
                    // 类型
                    var typeCell = document.createElement('td');
                    typeCell.textContent = formatCashflowType(cashflow.type);
                    row.appendChild(typeCell);
                    
                    // 金额
                    var amountCell = document.createElement('td');
                    amountCell.textContent = formatMoney(Math.abs(cashflow.amount));
                    row.appendChild(amountCell);
                    
                    // 流向
                    var directionCell = document.createElement('td');
                    directionCell.innerHTML = formatCashflowDirection(cashflow.is_outflow);
                    row.appendChild(directionCell);
                    
                    // 关联持仓
                    var relatedPositionCell = document.createElement('td');
                    relatedPositionCell.textContent = cashflow.related_position || '-';
                    row.appendChild(relatedPositionCell);
                    
                    cashflowsBody.appendChild(row);
                });
            });
        }
        
        // 格式化现金流类型
        function formatCashflowType(type) {
            switch(type) {
                case 'INTEREST':
                    return '利息';
                case 'PRINCIPAL':
                    return '本金';
                case 'MATURITY':
                    return '到期';
                default:
                    return type;
            }
        }
        
        // 格式化现金流方向
        function formatCashflowDirection(isOutflow) {
            return isOutflow ? '<span class="sell">流出</span>' : '<span class="buy">流入</span>';
        }
        
        // 绘制性能分析图表
        var perfData = $perf_plotly_json;
        Plotly.newPlot('perf-chart', perfData.data, perfData.layout);
        
        // 绘制持仓占比图表
        var posData = $pos_plotly_json;
        Plotly.newPlot('pos-chart', posData.data, posData.layout);
        
        // 标签页切换函数
        function openTab(evt, tabName) {
            // 保存当前标签页内容
            var activeTab = document.querySelector('.tab-content.active');
            if (activeTab) {
                var activeTabId = activeTab.id;
                if (activeTabId !== 'overview-tab') {
                    saveContentToCache(activeTabId);
                }
            }
            
            // 隐藏所有标签页内容
            var tabcontent = document.getElementsByClassName("tab-content");
            for (var i = 0; i < tabcontent.length; i++) {
                tabcontent[i].style.display = "none";
                tabcontent[i].classList.remove("active");
            }
            
            // 移除所有按钮的active类
            var tablinks = document.getElementsByClassName("tab-button");
            for (var i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace(" active", "");
            }
            
            // 显示当前标签页并标记按钮为活跃
            document.getElementById(tabName).style.display = "block";
            document.getElementById(tabName).classList.add("active");
            evt.currentTarget.className += " active";
            
            // 如果切换到概览标签页，重新绘制图表以确保正确显示
            if (tabName === 'overview-tab') {
                setTimeout(function() {
                    Plotly.relayout('perf-chart', {});
                    Plotly.relayout('pos-chart', {});
                }, 10);
                return; // 概览标签页无需额外加载
            }
            
            // 检查是否可以使用缓存
            var currentQueryParams = null;
            if (tabName === 'trades-tab') {
                currentQueryParams = {
                    startDate: document.getElementById('start-date-filter').value,
                    endDate: document.getElementById('end-date-filter').value
                };
            } else if (tabName === 'holdings-tab') {
                currentQueryParams = {
                    startDate: document.getElementById('holdings-start-date-filter').value,
                    endDate: document.getElementById('holdings-end-date-filter').value
                };
            } else if (tabName === 'cashflows-tab') {
                currentQueryParams = {
                    startDate: document.getElementById('cashflows-start-date-filter').value,
                    endDate: document.getElementById('cashflows-end-date-filter').value
                };
            }
            
            // 检查缓存并决定是否使用
            if (areQueryParamsEqual(tabsCache[tabName].queryParams, currentQueryParams) && tabsCache[tabName].content) {
                restoreContentFromCache(tabName);
                
                // 重新绑定事件监听器
                rebindEventListeners(tabName);
                return; // 使用缓存，无需重新加载
            }
            
            // 没有缓存或查询条件变化，显示加载动画并开始加载数据
            showLoading(tabName);
            
            // 使用setTimeout避免界面阻塞
            setTimeout(function() {
                // 根据标签页类型加载不同数据
                if (tabName === 'trades-tab') {
                    fillTradesTable(tradesData);
                } else if (tabName === 'holdings-tab') {
                    var initialStartDate = new Date(document.getElementById('holdings-start-date-filter').value);
                    var initialEndDate = new Date(document.getElementById('holdings-end-date-filter').value);
                    initialEndDate.setHours(23, 59, 59, 999);
                    fillHoldingsTable(holdingsData, initialStartDate, initialEndDate);
                } else if (tabName === 'cashflows-tab') {
                    var cashflowsStartDate = new Date(document.getElementById('cashflows-start-date-filter').value);
                    var cashflowsEndDate = new Date(document.getElementById('cashflows-end-date-filter').value);
                    cashflowsEndDate.setHours(23, 59, 59, 999);
                    fillCashflowsTable(cashflowsData, cashflowsStartDate, cashflowsEndDate);
                }
                
                // 标记该标签页已加载并保存到缓存
                tabsLoaded[tabName] = true;
                saveContentToCache(tabName);
                
                // 重新绑定事件监听器
                rebindEventListeners(tabName);
                
                // 隐藏加载动画
                hideLoading(tabName);
            }, 50); // 50ms的延迟，足够让界面更新
        }
        
        // 重新绑定事件监听器函数
        function rebindEventListeners(tabName) {
            if (tabName === 'trades-tab') {
                // 重新绑定交易记录过滤按钮事件监听器
                var filterTradesBtn = document.getElementById('filter-trades-btn');
                if (filterTradesBtn) {
                    filterTradesBtn.addEventListener('click', function() {
                        // 显示加载动画
                        showLoading('trades-tab');
                        
                        setTimeout(function() {
                            var startDate = new Date(document.getElementById('start-date-filter').value);
                            var endDate = new Date(document.getElementById('end-date-filter').value);
                            
                            // 设置结束日期为当天的最后一刻
                            endDate.setHours(23, 59, 59, 999);
                            
                            // 过滤交易记录
                            var filteredTrades = tradesData.filter(function(trade) {
                                var tradeDate = new Date(trade.timestamp);
                                return tradeDate >= startDate && tradeDate <= endDate;
                            });
                            
                            // 填充表格
                            fillTradesTable(filteredTrades);
                            
                            // 保存到缓存
                            var queryParams = {
                                startDate: document.getElementById('start-date-filter').value,
                                endDate: document.getElementById('end-date-filter').value
                            };
                            tabsCache['trades-tab'].queryParams = queryParams;
                            saveContentToCache('trades-tab');
                            
                            // 隐藏加载动画
                            hideLoading('trades-tab');
                        }, 50);
                    });
                }
            } else if (tabName === 'holdings-tab') {
                // 重新绑定持仓记录过滤按钮事件监听器
                var filterHoldingsBtn = document.getElementById('filter-holdings-btn');
                if (filterHoldingsBtn) {
                    filterHoldingsBtn.addEventListener('click', function() {
                        // 显示加载动画
                        showLoading('holdings-tab');
                        
                        setTimeout(function() {
                            var startDate = new Date(document.getElementById('holdings-start-date-filter').value);
                            var endDate = new Date(document.getElementById('holdings-end-date-filter').value);
                            
                            // 设置结束日期为当天的最后一刻
                            endDate.setHours(23, 59, 59, 999);
                            
                            // 填充表格
                            fillHoldingsTable(holdingsData, startDate, endDate);
                            
                            // 保存到缓存
                            var queryParams = {
                                startDate: document.getElementById('holdings-start-date-filter').value,
                                endDate: document.getElementById('holdings-end-date-filter').value
                            };
                            tabsCache['holdings-tab'].queryParams = queryParams;
                            saveContentToCache('holdings-tab');
                            
                            // 隐藏加载动画
                            hideLoading('holdings-tab');
                        }, 50);
                    });
                }
            } else if (tabName === 'cashflows-tab') {
                // 重新绑定现金流记录过滤按钮事件监听器
                var filterCashflowsBtn = document.getElementById('filter-cashflows-btn');
                if (filterCashflowsBtn) {
                    filterCashflowsBtn.addEventListener('click', function() {
                        // 显示加载动画
                        showLoading('cashflows-tab');
                        
                        setTimeout(function() {
                            var startDate = new Date(document.getElementById('cashflows-start-date-filter').value);
                            var endDate = new Date(document.getElementById('cashflows-end-date-filter').value);
                            
                            // 设置结束日期为当天的最后一刻
                            endDate.setHours(23, 59, 59, 999);
                            
                            // 过滤现金流记录
                            var filteredCashflows = cashflowsData.filter(function(cashflow) {
                                var cashflowDate = new Date(cashflow.timestamp);
                                return cashflowDate >= startDate && cashflowDate <= endDate;
                            });
                            
                            // 填充表格
                            fillCashflowsTable(filteredCashflows, startDate, endDate);
                            
                            // 保存到缓存
                            var queryParams = {
                                startDate: document.getElementById('cashflows-start-date-filter').value,
                                endDate: document.getElementById('cashflows-end-date-filter').value
                            };
                            tabsCache['cashflows-tab'].queryParams = queryParams;
                            saveContentToCache('cashflows-tab');
                            
                            // 隐藏加载动画
                            hideLoading('cashflows-tab');
                        }, 50);
                    });
                }
            }
        }
        
        // 检查查询条件是否与缓存一致
        function areQueryParamsEqual(cache, current) {
            if (!cache || !current) return false;
            return JSON.stringify(cache) === JSON.stringify(current);
        }
        
        // 保存当前的DOM内容到缓存
        function saveContentToCache(tabId) {
            var tabContent = document.getElementById(tabId).innerHTML;
            
            // 确保存在缓存对象
            if (!tabsCache[tabId]) {
                tabsCache[tabId] = {
                    content: '',
                    queryParams: {},
                    scrollPosition: 0 // 保存滚动位置
                };
            }
            
            // 保存日期选择框的值
            if (tabId === 'trades-tab') {
                tabsCache[tabId].queryParams = {
                    startDate: document.getElementById('start-date-filter').value,
                    endDate: document.getElementById('end-date-filter').value
                };
                // 保存滚动位置 - 交易记录表格容器
                var container = document.getElementById('trades-table-container');
                if (container) {
                    tabsCache[tabId].scrollPosition = container.scrollTop;
                }
            } else if (tabId === 'holdings-tab') {
                tabsCache[tabId].queryParams = {
                    startDate: document.getElementById('holdings-start-date-filter').value,
                    endDate: document.getElementById('holdings-end-date-filter').value
                };
                // 保存滚动位置 - 持仓记录表格容器
                var container = document.getElementById('holdings-table-container');
                if (container) {
                    tabsCache[tabId].scrollPosition = container.scrollTop;
                }
            } else if (tabId === 'cashflows-tab') {
                tabsCache[tabId].queryParams = {
                    startDate: document.getElementById('cashflows-start-date-filter').value,
                    endDate: document.getElementById('cashflows-end-date-filter').value
                };
                // 保存滚动位置 - 现金流记录表格容器
                var container = document.getElementById('cashflows-table-container');
                if (container) {
                    tabsCache[tabId].scrollPosition = container.scrollTop;
                }
            }
            
            // 保存内容
            tabsCache[tabId].content = tabContent;
        }
        
        // 从缓存恢复内容
        function restoreContentFromCache(tabId) {
            if (tabsCache[tabId] && tabsCache[tabId].content) {
                document.getElementById(tabId).innerHTML = tabsCache[tabId].content;
                
                // 恢复日期选择框的值
                if (tabId === 'trades-tab' && tabsCache[tabId].queryParams) {
                    if (document.getElementById('start-date-filter') && tabsCache[tabId].queryParams.startDate) {
                        document.getElementById('start-date-filter').value = tabsCache[tabId].queryParams.startDate;
                    }
                    if (document.getElementById('end-date-filter') && tabsCache[tabId].queryParams.endDate) {
                        document.getElementById('end-date-filter').value = tabsCache[tabId].queryParams.endDate;
                    }
                    // 恢复滚动位置 - 交易记录表格容器
                    setTimeout(function() {
                        var container = document.getElementById('trades-table-container');
                        if (container && tabsCache[tabId].scrollPosition) {
                            container.scrollTop = tabsCache[tabId].scrollPosition;
                        }
                    }, 10); // 短暂延迟确保DOM已更新
                } else if (tabId === 'holdings-tab' && tabsCache[tabId].queryParams) {
                    if (document.getElementById('holdings-start-date-filter') && tabsCache[tabId].queryParams.startDate) {
                        document.getElementById('holdings-start-date-filter').value = tabsCache[tabId].queryParams.startDate;
                    }
                    if (document.getElementById('holdings-end-date-filter') && tabsCache[tabId].queryParams.endDate) {
                        document.getElementById('holdings-end-date-filter').value = tabsCache[tabId].queryParams.endDate;
                    }
                    // 恢复滚动位置 - 持仓记录表格容器
                    setTimeout(function() {
                        var container = document.getElementById('holdings-table-container');
                        if (container && tabsCache[tabId].scrollPosition) {
                            container.scrollTop = tabsCache[tabId].scrollPosition;
                        }
                    }, 10); // 短暂延迟确保DOM已更新
                } else if (tabId === 'cashflows-tab' && tabsCache[tabId].queryParams) {
                    if (document.getElementById('cashflows-start-date-filter') && tabsCache[tabId].queryParams.startDate) {
                        document.getElementById('cashflows-start-date-filter').value = tabsCache[tabId].queryParams.startDate;
                    }
                    if (document.getElementById('cashflows-end-date-filter') && tabsCache[tabId].queryParams.endDate) {
                        document.getElementById('cashflows-end-date-filter').value = tabsCache[tabId].queryParams.endDate;
                    }
                    // 恢复滚动位置 - 现金流记录表格容器
                    setTimeout(function() {
                        var container = document.getElementById('cashflows-table-container');
                        if (container && tabsCache[tabId].scrollPosition) {
                            container.scrollTop = tabsCache[tabId].scrollPosition;
                        }
                    }, 10); // 短暂延迟确保DOM已更新
                }
            }
        }
        
        // 添加交易记录过滤功能
        document.getElementById('filter-trades-btn').addEventListener('click', function() {
            // 显示加载动画
            showLoading('trades-tab');
            
            setTimeout(function() {
                var startDate = new Date(document.getElementById('start-date-filter').value);
                var endDate = new Date(document.getElementById('end-date-filter').value);
                
                // 设置结束日期为当天的最后一刻
                endDate.setHours(23, 59, 59, 999);
                
                // 过滤交易记录
                var filteredTrades = tradesData.filter(function(trade) {
                    var tradeDate = new Date(trade.timestamp);
                    return tradeDate >= startDate && tradeDate <= endDate;
                });
                
                // 填充表格
                fillTradesTable(filteredTrades);
                
                // 保存到缓存
                var queryParams = {
                    startDate: document.getElementById('start-date-filter').value,
                    endDate: document.getElementById('end-date-filter').value
                };
                tabsCache['trades-tab'].queryParams = queryParams;
                saveContentToCache('trades-tab');
                
                // 隐藏加载动画
                hideLoading('trades-tab');
            }, 50);
        });
        
        // 添加持仓记录过滤功能
        document.getElementById('filter-holdings-btn').addEventListener('click', function() {
            // 显示加载动画
            showLoading('holdings-tab');
            
            setTimeout(function() {
                var startDate = new Date(document.getElementById('holdings-start-date-filter').value);
                var endDate = new Date(document.getElementById('holdings-end-date-filter').value);
                
                // 设置结束日期为当天的最后一刻
                endDate.setHours(23, 59, 59, 999);
                
                // 填充表格
                fillHoldingsTable(holdingsData, startDate, endDate);
                
                // 保存到缓存
                var queryParams = {
                    startDate: document.getElementById('holdings-start-date-filter').value,
                    endDate: document.getElementById('holdings-end-date-filter').value
                };
                tabsCache['holdings-tab'].queryParams = queryParams;
                saveContentToCache('holdings-tab');
                
                // 隐藏加载动画
                hideLoading('holdings-tab');
            }, 50);
        });
        
        // 添加现金流记录过滤功能
        document.getElementById('filter-cashflows-btn').addEventListener('click', function() {
            // 显示加载动画
            showLoading('cashflows-tab');
            
            setTimeout(function() {
                var startDate = new Date(document.getElementById('cashflows-start-date-filter').value);
                var endDate = new Date(document.getElementById('cashflows-end-date-filter').value);
                
                // 设置结束日期为当天的最后一刻
                endDate.setHours(23, 59, 59, 999);
                
                // 过滤现金流记录
                var filteredCashflows = cashflowsData.filter(function(cashflow) {
                    var cashflowDate = new Date(cashflow.timestamp);
                    return cashflowDate >= startDate && cashflowDate <= endDate;
                });
                
                // 填充表格
                fillCashflowsTable(filteredCashflows, startDate, endDate);
                
                // 保存到缓存
                var queryParams = {
                    startDate: document.getElementById('cashflows-start-date-filter').value,
                    endDate: document.getElementById('cashflows-end-date-filter').value
                };
                tabsCache['cashflows-tab'].queryParams = queryParams;
                saveContentToCache('cashflows-tab');
                
                // 隐藏加载动画
                hideLoading('cashflows-tab');
            }, 50);
        });
        
        // 为指标卡片添加交互
        document.addEventListener('DOMContentLoaded', function() {
            // 添加下载净值数据按钮事件
            document.getElementById('download-netvalue-btn').addEventListener('click', function() {
                downloadNetValueData();
            });
            
            // 处理负数值显示为绿色
            var metricValues = document.querySelectorAll('.metric-value');
            metricValues.forEach(function(element) {
                var text = element.textContent.trim();
                // 检查是否为负数（以'-'开头）
                if (text.startsWith('-')) {
                    element.classList.add('negative-value');
                }
            });

            // 添加悬停提示
            var tooltipDescriptions = {
                '总收益率': '投资期间的总收益百分比',
                '年化收益率': '将总收益换算为年化的收益率',
                '最大回撤': '策略在回测期间的最大亏损百分比',
                '夏普比率': '每承担一单位总风险，能获得多少超额回报',
                '索提诺比率': '类似夏普比率，但只考虑下行风险',
                '卡玛比率': '年化收益率与最大回撤的比率',
                '年化波动率': '收益率的年化标准差',
                '胜率': '盈利交易占总交易的百分比',
                '换手率': '年化的持仓更替率，反映交易频率',
                '平均持仓标的数': '策略平均持有的债券标的数量'
            };

            var metricCards = document.querySelectorAll('.metric-card');
            var tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            document.body.appendChild(tooltip);

            metricCards.forEach(function(card) {
                var metricTitle = card.querySelector('h3').textContent;
                
                card.addEventListener('mouseover', function(e) {
                    if (tooltipDescriptions[metricTitle]) {
                        tooltip.textContent = tooltipDescriptions[metricTitle];
                        tooltip.style.display = 'block';
                        tooltip.style.left = e.pageX + 10 + 'px';
                        tooltip.style.top = e.pageY + 10 + 'px';
                    }
                });

                card.addEventListener('mousemove', function(e) {
                    tooltip.style.left = e.pageX + 10 + 'px';
                    tooltip.style.top = e.pageY + 10 + 'px';
                });

                card.addEventListener('mouseout', function() {
                    tooltip.style.display = 'none';
                });
            });
        });
        
        // u9875u9762u52a0u8f7du5b8cu6210u540eu7684u51fdu6570
        document.addEventListener('DOMContentLoaded', function() {
            // u9ed8u8ba4u9009u4e2du7b2cu4e00u4e2au6807u7b7eu9875u5e76u5c55u793au6982u89c8
            document.getElementById("defaultOpen").click();
            
            // u5f02u6b65u52a0u8f7du5176u4ed6u6807u7b7eu9875u6570u636n
            setTimeout(function() {
                preloadAllTabsData();
            }, 500); // u7b49u5f85u6982u89c8u9875u52a0u8f7du5b8cu518du52a0u8f7du5176u4ed6u6807u7b7eu9875
        });
        
        // u9884u52a0u8f7du6240u6709u6807u7b7eu9875u6570u636eu7684u51fdu6570
        function preloadAllTabsData() {
            console.log('u5f00u59cbu9884u52a0u8f7du6240u6709u6807u7b7eu9875u6570u636e...');
            
            // u4f7fu7528Promise.allu5e76u884cu52a0u8f7du6240u6709u6807u7b7eu9875u6570u636e
            Promise.all([
                preloadTabData('trades-tab'),
                preloadTabData('holdings-tab'),
                preloadTabData('cashflows-tab')
            ]).then(function() {
                console.log('u6240u6709u6807u7b7eu9875u6570u636eu9884u52a0u8f7du5b8cu6210');
            }).catch(function(error) {
                console.error('u6570u636eu9884u52a0u8f7du5931u8d25:', error);
            });
        }
        
        // u9884u52a0u8f7du5355u4e2au6807u7b7eu9875u6570u636e
        function preloadTabData(tabName) {
            return new Promise(function(resolve, reject) {
                try {
                    console.log('u6b63u5728u9884u52a0u8f7d ' + tabName + ' u6570u636e...');
                    
                    if (tabName === 'trades-tab') {
                        fillTradesTable(tradesData);
                        tabsLoaded[tabName] = true;
                        saveContentToCache(tabName);
                    } else if (tabName === 'holdings-tab') {
                        var initialStartDate = new Date(document.getElementById('holdings-start-date-filter').value);
                        var initialEndDate = new Date(document.getElementById('holdings-end-date-filter').value);
                        initialEndDate.setHours(23, 59, 59, 999);
                        fillHoldingsTable(holdingsData, initialStartDate, initialEndDate);
                        tabsLoaded[tabName] = true;
                        saveContentToCache(tabName);
                    } else if (tabName === 'cashflows-tab') {
                        var cashflowsStartDate = new Date(document.getElementById('cashflows-start-date-filter').value);
                        var cashflowsEndDate = new Date(document.getElementById('cashflows-end-date-filter').value);
                        cashflowsEndDate.setHours(23, 59, 59, 999);
                        fillCashflowsTable(cashflowsData, cashflowsStartDate, cashflowsEndDate);
                        tabsLoaded[tabName] = true;
                        saveContentToCache(tabName);
                    }
                    
                    console.log(tabName + ' u6570u636eu9884u52a0u8f7du5b8cu6210');
                    resolve();
                } catch (error) {
                    console.error(tabName + ' u6570u636eu9884u52a0u8f7du5931u8d25:', error);
                    reject(error);
                }
            });
        }
        
        // 下载净值数据为Excel文件
        function downloadNetValueData() {
            try {
                // 检查是否有性能数据
                if (!perfPlotlyData || !perfPlotlyData.data) {
                    alert('没有可用的净值数据');
                    return;
                }
                
                // 查找净值曲线数据
                var netValueTrace = null;
                for (var i = 0; i < perfPlotlyData.data.length; i++) {
                    if (perfPlotlyData.data[i].name === '总资产') {
                        netValueTrace = perfPlotlyData.data[i];
                        break;
                    }
                }
                
                if (!netValueTrace || !netValueTrace.x || !netValueTrace.y) {
                    alert('无法找到净值曲线数据');
                    return;
                }
                
                // 准备Excel数据
                var excelData = [];
                var headers = ['日期', '净值'];
                excelData.push(headers);
                
                // 添加数据行
                for (var j = 0; j < netValueTrace.x.length; j++) {
                    var date = new Date(netValueTrace.x[j]);
                    var formattedDate = date.getFullYear() + '-' + 
                                       String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                                       String(date.getDate()).padStart(2, '0');
                    var value = netValueTrace.y[j];
                    excelData.push([formattedDate, value]);
                }
                
                // 创建工作表
                var ws = XLSX.utils.aoa_to_sheet(excelData);
                
                // 创建工作簿
                var wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, '每日净值');
                
                // 生成Excel文件并下载
                var fileName = '每日净值数据_' + new Date().toISOString().slice(0, 10) + '.xlsx';
                XLSX.writeFile(wb, fileName);
            } catch (error) {
                console.error('导出净值数据失败:', error);
                alert('导出净值数据失败: ' + error.message);
                
                // 如果导出失败，尝试使用CSV格式
                tryExportAsCSV(netValueTrace);
            }
        }
        
        // 备用CSV导出方法
        function tryExportAsCSV(netValueTrace) {
            try {
                if (!netValueTrace || !netValueTrace.x || !netValueTrace.y) {
                    return;
                }
                
                // 创建CSV内容
                var csvContent = '日期,净值\n';
                
                // 添加数据行
                for (var j = 0; j < netValueTrace.x.length; j++) {
                    var date = new Date(netValueTrace.x[j]);
                    var formattedDate = date.getFullYear() + '-' + 
                                    String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                                    String(date.getDate()).padStart(2, '0');
                    var value = netValueTrace.y[j];
                    csvContent += formattedDate + ',' + value + '\n';
                }
                
                // 创建Blob对象
                var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                
                // 创建下载链接
                var link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = '每日净值数据_' + new Date().toISOString().slice(0, 10) + '.csv';
                link.style.display = 'none';
                document.body.appendChild(link);
                
                // 触发下载
                link.click();
                
                // 清理
                document.body.removeChild(link);
            } catch (error) {
                console.error('导出CSV失败:', error);
                alert('导出数据失败，请稍后再试');
            }
        }
    </script>
    
    <!-- 添加SheetJS库用于Excel导出 -->
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
</body>
</html>
